package com.kvn.reflect.benchmark;

import com.kvn.reflect.FieldAccess;
import com.kvn.reflect.FooService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

/**
 * Created by wangzhiyuan on 2019/2/14
 */
@Warmup(iterations = 3, time = 10)
@Measurement(iterations = 3, time = 10)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class FieldAccessBeanchmark {

    private FooService fooService;

    @Setup
    public void prepare() {
        fooService = new FooService();
        fooService.setStringParam1(RandomStringUtils.randomAlphabetic(4));
        fooService.setIntParam2(RandomUtils.nextInt(1, 10000));
    }

    @Benchmark
    @Threads(1)
    public void test1ThreadDoSomethingWithJdkReflect() throws Exception {
        FooService.class.getMethod("getIntParam2").invoke(fooService);
        FooService.class.getMethod("getStringParam1").invoke(fooService);
    }

    @Benchmark
    @Threads(1)
    public void test1ThreadDoSomethingWithHpReflect(){
        FieldAccess.get(FooService.class).get(fooService, "intParam2");
        FieldAccess.get(FooService.class).get(fooService, "stringParam1");
    }

    @Benchmark
    @Threads(2)
    public void test2ThreadsDoSomethingWithJdkReflect() throws Exception {
        FooService.class.getMethod("getIntParam2").invoke(fooService);
        FooService.class.getMethod("getStringParam1").invoke(fooService);
    }

    @Benchmark
    @Threads(2)
    public void test2ThreadsDoSomethingWithHpReflect(){
        FieldAccess.get(FooService.class).get(fooService, "intParam2");
        FieldAccess.get(FooService.class).get(fooService, "stringParam1");
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(FieldAccessBeanchmark.class.getSimpleName())
                .forks(1) // 启动测试进程数，比如@Fork(2)，那么JMH会启动两个进程进行测试
                .output("E:/FieldAccessBeanchmark.log")
                .build();

        new Runner(opt).run();
    }

}
